package com.gitee.ywj1352.算法.week01;

/**
 * Given n non-negative integers representing an elevation map
 * where the width of each bar is 1, compute how much water it can trap after raining.
 * <p>
 * https://leetcode.com/problems/trapping-rain-water/
 */
public class TrappingRainWater {

    /**
     * 接雨水
     *
     * @param height
     * @return
     */
    public static int trap(int[] height) {
        if (height.length == 0) return 0;
        int L = 1, R = height.length - 2, count = 0;
        int maxL = height[0];
        int maxR = height[height.length - 1];
        int cm = 0;
        for (int i = 0; i < height.length; i++) {
            if (height[cm] < height[i]) {
                cm = i;
            }
        }
        while (L < cm) {
            if (height[L] > maxL) {
                maxL = height[L];
            } else {
                count += maxL - height[L];
            }
            L++;
        }
        while (R > cm) {
            if (height[R] > maxR) {
                maxR = height[R];
            } else {
                count += maxR - height[R];
            }
            R--;
        }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        System.out.println(trap(arr));
    }
}
